import { Button, Input } from "@tarojs/components";
import React, { createRef, useEffect, useRef, useState } from "react";
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui";
import Taro from "@tarojs/taro";
import classNames from "classnames";
import { getLastInvitation, instance, setStore } from "../../../src/utils";
import { ILoginResponse, IRandomCodeBody } from "../../../src/interfaces";
import "./index.scss";
import {
  CheckCheckShareInfo,
  fetchCheckFileShareInfo,
  fetchIsRegister,
  fetchOuterMember,
  fetchUserInfo,
  fetchVerification,
} from "../../../src/api";

interface Props {
  /** 点击登录 */
  onLogin: () => void;
}
export const LoginCard = ({ onLogin }: Props) => {
  const [projectName, setProjectName] = useState("");
  const inputRef = createRef<HTMLInputElement>();
  const { router } = Taro.getCurrentInstance();
  const [phone, setPhone] = useState("");
  const [isPhoneFocus, setIsPhoneFocus] = useState(false);
  const [isCodeFocus, setIsCodeFocus] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const countdownRef = useRef(0);
  const [isRegister, setIsRegister] = useState(false);
  const [showflag, setShowflag] = useState(false);
  // const [showClose, setShowClose] = useState(true);

  const [urlstr, setUrlstr] = useState("");

  const handlePhoneInput = (e) => {
    const { value } = e.target;
    let val = (value as string).replace(/[^\d]/g, "");
    if (val.length > 3) {
      val = val.replace(/^(\d{3})/g, "$1 ");
    }
    if (val.length > 8) {
      val = val.replace(/^([\d ]{8})/g, "$1 ");
    }
    if (val.length > 13) {
      val = val.slice(0, 13);
    }
    setPhone(val);
  };
  const [code, setCode] = useState("");

  useEffect(() => {
    const invitation = getLastInvitation();
    if (!invitation || !invitation.type) return;
    const info = invitation[invitation.type];
    if (!info) return;

    setProjectName(info.projectName || "");
  }, []);
  const handleCodeInput = (e) => {
    const { value } = e.target;
    setCode(value.substr(0, 6));
  };
  const getGreeting = () => {
    const date = new Date();
    const h = date.getHours();
    // const m = date.getMinutes();
    if (h >= 0 && h < 9) return "早上好";
    if (h >= 9 && h < 11) return "上午好";
    if (h >= 11 && h < 13) return "中午好";
    if (h >= 13 && h < 19) return "下午好";
    if (h >= 19 && h <= 23) return "晚上好";
  };
  /** 获取验证码 */
  const handleGetCode = async () => {
    if (countdownRef.current > 0 || !phone) return;
    const body: IRandomCodeBody = {
      phoneNumber: phone.replace(/[^\d]/g, ""),
      msgCode: "register",
    };
    /** 发送验证码 */
    const {
      code: _code,
      data,
      message,
    } = await instance.post("/sms/randomCode", body).then((res) => res.data);
    if (_code !== 0) {
      console.log("error", message);
      return;
    }
    setCountdown(60);
    countdownRef.current = 60;
    const timer = setInterval(() => {
      const newCountdown = countdownRef.current - 1;
      countdownRef.current = newCountdown;
      setCountdown(newCountdown);
      if (newCountdown === 0) {
        clearInterval(timer);
      }
    }, 1000);

    const { data: registerData } = await fetchIsRegister(
      phone.replace(/[^\d]/g, "")
    );
    setIsRegister(registerData.isExist);
  };
  // 关闭弹窗事件
  const handleClose = () => {
    setShowflag(false);

  }
  const handleLogin = async () => {
    if (!isRegister) {
      // 未注册，到注册页面
      const verificationRes = await fetchVerification(
        phone.replace(/[^\d]/g, ""),
        code
      );
      if (verificationRes.code !== 0) {
        alert(verificationRes.message);
        return;
      }
      sessionStorage.setItem("register-phone", phone.replace(/[^\d]/g, ""));
      sessionStorage.setItem("register-code", code);
      let url = router!.params.from || "";
      if (Array.isArray(url)) {
        url = url[url.length - 1];
      }
      Taro.navigateTo({
        url: `pages/project-register/index?from=${encodeURIComponent(url)}`,
      });
      return;
    }
    const body: any = {
      phoneNumber: phone.replace(/[^\d]/g, ""),
      msgCode: "register",
      randomCode: code,
      loginType: "phoneNumberAndRandomCode",
      clientType: "web",
      invitation: true,
    };
    if (router && router.params && router.params.referenceId) {
      body.referenceId = router.params.referenceId;
      body.invitation = true;
    }
    instance
      .post("/user/token", body)
      .then(({ data }) => data)
      .then(async ({ code: _code, data, message }) => {
        if (_code !== 0) {
          alert(message);
          return;
        }
        const { accessToken, pubKey } = data as ILoginResponse;
        setStore("token", accessToken);
        setStore("pubRsaKey", pubKey);

        if (router && router.params && router.params.from) {
          let url = router.params.from;
          if (Array.isArray(router.params.from)) {
            url = router.params.from[router.params.from.length - 1];
          }
          if (url.indexOf("project-share/index") > -1) {
            // 项目分享，校验权限、跳转
            const referenceId = router.params.from.match(/referenceId=([^&]+)/);
            const _paramPassword =
              sessionStorage.getItem("project-watch") || "";
            const _paramId = sessionStorage.getItem("project-watch-id") || "";
            const projectRes = await fetchOuterMember(_paramId, {
              password: _paramPassword,
              referenceId: (referenceId && referenceId[1]) || "",
            });
            if (projectRes.code !== 0) {
              alert(projectRes.message);
              return;
            }

            if (projectRes.data.memberType === "in") {
              setShowflag(true);
            } else {
              Taro.navigateTo({
                url: `/pages/index/index?spaceId=${projectRes.data.spaceId}`,
              });
            }
          } else if (url.indexOf("file-share/index") > -1) {
            // 文件分享，校验权限、跳转
            const shareIdMatch = router.params.from.match(/shareId=([^&]+)/);
            const _paramPassword = sessionStorage.getItem("file-watch") || "";
            const fileRes = await fetchCheckFileShareInfo(
              (shareIdMatch && shareIdMatch[1]) || "",
              _paramPassword ? { password: _paramPassword } : {}
            );
            if (fileRes.code !== 0) {
              alert(fileRes.message);
              return;
            }
            const { accessKey, spaceId, channelId, dirId } = fileRes.data;
            Taro.navigateTo({
              url: `/pages/file-index/index?shareId=${shareIdMatch && shareIdMatch[1]
                }&spaceId=${spaceId}&accessKey=${accessKey}&channelId=${channelId}&dirId=${dirId}`,
            });
          } else if (url.indexOf("check-share/index") > -1) {
            // 确认分享，校验权限、跳转
            const listingIdMatch =
              router.params.from.match(/listingId=([^&]+)/);
            const listingId = (listingIdMatch && listingIdMatch[1]) || "";
            const shareIdMatch = router.params.from.match(/shareId=([^&]+)/);
            const shareId = (shareIdMatch && shareIdMatch[1]) || "";
            const _paramPassword = sessionStorage.getItem("check-watch") || "";
            const _paramId = sessionStorage.getItem("check-watch-id") || "";
            const spaceId = sessionStorage.getItem("check-spaceid") || "";
            const checkRes = await CheckCheckShareInfo(
              _paramId,
              listingId,
              shareId,
              _paramPassword ? { password: _paramPassword } : {}
            );
            console.log("handleLogin -> checkRes", checkRes);
            try {
              Taro.setStorageSync("accessKey", checkRes.data.accessKey);
            } catch (e) { }
            if (checkRes.code !== 0) {
              alert(checkRes.message);
              return;
            }
            if (checkRes.data.memberType && checkRes.data.memberType === "in") {
              setShowflag(true);
            } else {
              Taro.navigateTo({
                url: `/pages/check-index/index?spaceId=${spaceId}&shareId=${shareId}&listingId=${listingId}`,
              });
            }
          } else {
            Taro.navigateTo({
              url: `${url}&login=true`,
            });
          }
        } else if (onLogin) {
          onLogin();
        }
      });
  };

  return (
    <div className="login-card">
      {/* <AtModal
        isOpened={showflag}
        // isOpened
        cancelText='取消'
        confirmText='确认'
        content='您是项目内部成员，暂不支持移动端查看，请去pc端查看'
        <AtModalContent><a href=""></a></AtModalContent>
        content={urlstr}
      /> */}
      <AtModal isOpened={showflag} closeOnClickOverlay={true} onClose={(handleClose)}>
        <AtModalContent>
          您是项目内部成员，暂不支持移动端查看，请去pc端,
          <a target="_blank" href="https://web.mingque.com">
            web.mingque.com
          </a>
          查看
        </AtModalContent>
        {/* <AtModalAction>  <Button onConfirm={() => { jumpother() }}></Button> </AtModalAction> */}
      </AtModal>
      <div className="greeting">{getGreeting()}</div>
      <div className="company">{projectName}</div>
      <div className="phone-area">
        <div className="area">+86</div>
        <input
          ref={inputRef}
          className={classNames("phone", "login-input", {
            placeholder: !phone,
          })}
          onInput={handlePhoneInput}
          onFocus={() => setIsPhoneFocus(true)}
          onBlur={() => {
            setTimeout(() => {
              setIsPhoneFocus(false);
            });
          }}
          autoComplete="off"
          placeholder={isPhoneFocus ? "" : "请输入手机号"}
          value={phone}
        ></input>
        <span
          onClick={() => {
            setPhone("");
            setTimeout(() => {
              if (inputRef.current) {
                inputRef.current?.focus();
              } else {
                const inp = document.getElementsByClassName(
                  "login-input"
                )[0] as HTMLInputElement;
                if (inp && inp.focus) {
                  inp.focus();
                }
              }
            });
          }}
          className={classNames("iconfont", "icon-error", {
            hidden: !phone || !isPhoneFocus,
          })}
        ></span>
      </div>
      <div className="verification">
        <input
          type="text"
          className={classNames("code", {
            placeholder: !code,
          })}
          onInput={handleCodeInput}
          onFocus={() => setIsCodeFocus(true)}
          onBlur={() => setIsCodeFocus(false)}
          placeholder={isCodeFocus ? "" : "请输入验证码"}
          value={code}
          autoComplete="off"
        ></input>
        <div
          className={classNames("get-code", {
            active: phone && phone.length === 13 && countdown === 0,
            countdown: countdown > 0,
          })}
          onClick={handleGetCode}
        >
          {countdown > 0 ? countdown : "获取验证码"}
        </div>
      </div>
      <Button
        disabled={!phone || !code}
        className={classNames("login", {
          active: !!phone && !!code,
        })}
        onClick={(!!phone && !!code && handleLogin) || undefined}
      >
        登录
      </Button>
    </div>
  );
};
